import { reqGetCode, reqUserLogin, reqUserRegister,reqGetUserInfo, reqUserLogout,reqUserAddressList} from '@/api'
import {getUserTempId} from '@/utils/userAbout'
const state = {
  // 初始化的时候就获取用户的临时标识存储到这里
  userTempId:getUserTempId(),
  code:'',
  // token:'', 初始化为空串我们是做登录，但是如果要自动登录，那么就要先从localStorage取
  token:localStorage.getItem('TOKEN_KEY'),
  userInfo:{},
  userAddressList:[]

}
const mutations = {
  RECEIVE_CODE(state,code){
    state.code = code
  },

  RECEIVE_TOKEN(state,token){
    state.token = token
  },

  RECEIVE_USERINFO(state,userInfo){
    state.userInfo = userInfo
  },

  RESET_TOKEN(state){
    state.token = ''
    state.userInfo = {}
  },

  //获取用户收货地址，在交易页面使用
  RECEIVE_USERADDRESSLIST(state,userAddressList){
    state.userAddressList = userAddressList
  }

}
const actions = {
  async getCode({commit},phone){
    const result = await reqGetCode(phone)
    if(result.code === 200){
      commit('RECEIVE_CODE',result.data)
      return result.data
    }else{
      return Promise.reject(new Error('failed'))
    }
  },

  async userRegister({commit},userInfo){
    const result = await reqUserRegister(userInfo)
    if(result.code === 200){
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },


  async userLogin({commit},userInfo){
    const result = await reqUserLogin(userInfo)
    if(result.code === 200){
      commit('RECEIVE_TOKEN',result.data.token)
      //要想自动登录，这里拿到token必须往localStorage内部也存储一次
      localStorage.setItem('TOKEN_KEY',result.data.token)
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },

  //获取用户信息
  async getUserInfo({commit}){
    const result = await reqGetUserInfo()
    if(result.code === 200){
      commit('RECEIVE_USERINFO',result.data)
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },

  //清空token
  async resetToken({commit}){
    commit('RESET_TOKEN') //清空state内部的额token
    localStorage.removeItem('TOKEN_KEY') //清空localStorage内部的token信息
  },

  //退出登录
  async userLogout({commit,dispatch}){
    const result = await reqUserLogout()
    if(result.code === 200){
      dispatch('resetToken') 
      //退成登录成功，清空当前state当中的token和用户信息，还有localStorage内部的token信息
      return 'ok'
    }else{
      return Promise.reject(new Error('failed'))
    }
  },


  //获取用户收货地址
  async getUserAddressList({commit}){
    const result = await reqUserAddressList()
    if(result.code === 200){
      commit('RECEIVE_USERADDRESSLIST',result.data)
    }
  }
}
const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}